package com.colin.aiyi.ui.personal;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.colin.aiyi.R;
import com.colin.aiyi.app.Constant;
import com.colin.aiyi.entity.User;
import com.colin.aiyi.entity.response.BaseResponse;
import com.colin.aiyi.presenter.AbsP;
import com.colin.aiyi.ui.ProvinceAc;
import com.colin.aiyi.ui.login.LoginAc;
import com.colin.aiyi.utils.SharePreferenceUtil;
import com.colin.aiyi.utils.TimeUtil;
import com.colin.aiyi.view.ShowMsgUtil;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by hl on 2017/6/7.
 */

public class PersonalAc extends TakePhotoActivity implements View.OnClickListener{
    @BindView(R.id.img_head)
    CircleImageView imgHead;
    @BindView(R.id.item_name1)
    LinearLayout itemName1;
    @BindView(R.id.item_name3)
    LinearLayout itemName3;
    @BindView(R.id.item_name4)
    LinearLayout itemName4;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.item_name5)
    LinearLayout itemName5;
    @BindView(R.id.item_name6)
    LinearLayout itemName6;
    @BindView(R.id.button_send)
    Button buttonSend;
    @BindView(R.id.text_name)
    EditText textName;
    @BindView(R.id.text_sex)
    TextView textSex;
    @BindView(R.id.text_date)
    TextView textDate;
    @BindView(R.id.text_star)
    TextView textStar;
    @BindView(R.id.text_city)
    TextView textCity;
    @BindView(R.id.text_banner_left)
    TextView textBannerLeft;
    @BindView(R.id.text_banner_title)
    TextView textBannerTitle;
    @BindView(R.id.text_banner_rigth)
    TextView textBannerRigth;
    @BindView(R.id.text_next1)
    TextView textNext1;
    @BindView(R.id.text_next2)
    TextView textNext2;
    @BindView(R.id.text_next3)
    TextView textNext3;
    @BindView(R.id.text_next4)
    TextView textNext4;
    @BindView(R.id.item_name2)
    RelativeLayout itemName2;
    private TimePickerView pvTime;
    private OptionsPickerView pvNoLinkOptions;
    private AlertDialog alertDialog;
    User user;
    private boolean isEdit=false;
    private long exitTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_personal);
        ButterKnife.bind(this);
        textBannerTitle.setText("个人资料");
        textBannerLeft.setOnClickListener(this);
        textBannerRigth.setOnClickListener(this);
        textBannerRigth.setText("编辑");
        user = SharePreferenceUtil.getObject(this, User.class);
        user.setBirthbay(new Date().getTime());
        bindView(user);
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }
    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    void bindView(User user) {
        if (user == null)
            return;
        Glide.with(this).load(Constant.BASE_URL + user.getHeadUrl()).error(R.mipmap.pic2).into(imgHead);
        try {
            textName.setText(user.getUserName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        textSex.setText(user.getSex() == 1 ? "男" : "女");
        textDate.setText(TimeUtil.getTime(new Date(user.getBirthbay())));
        try {
            textCity.setText(user.getCityName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void swichStatus(boolean isEdit) {
        if (isEdit) {
            textBannerTitle.setText("修改资料");
            textBannerRigth.setVisibility(View.GONE);
            textNext1.setVisibility(View.VISIBLE);
            textNext2.setVisibility(View.VISIBLE);
            textNext3.setVisibility(View.VISIBLE);
            textNext4.setVisibility(View.VISIBLE);
            textName.setFocusable(true);
            textName.setClickable(true);
            textName.setEnabled(true);
            textName.setFocusableInTouchMode(true);
           // textName.requestFocus();
//            textName.setGravity(Gravity.LEFT |Gravity.CENTER_VERTICAL);
            textName.setSelection(textName.getText().length());
            textName.setTextColor(getResources().getColor(R.color.c9999));
            textSex.setTextColor(getResources().getColor(R.color.c9999));
            textDate.setTextColor(getResources().getColor(R.color.c9999));
            textStar.setTextColor(getResources().getColor(R.color.c9999));
            textCity.setTextColor(getResources().getColor(R.color.c9999));
            buttonSend.setVisibility(View.VISIBLE);

        } else {
            textBannerTitle.setText("个人资料");
            textBannerRigth.setVisibility(View.VISIBLE);
            textNext1.setVisibility(View.GONE);
            textNext2.setVisibility(View.GONE);
            textNext3.setVisibility(View.GONE);
            textNext4.setVisibility(View.GONE);
            textName.setClickable(false);
            textName.setFocusable(false);
            textName.setTextColor(getResources().getColor(R.color.c3333));
            textSex.setTextColor(getResources().getColor(R.color.c3333));
            textDate.setTextColor(getResources().getColor(R.color.c3333));
            textStar.setTextColor(getResources().getColor(R.color.c3333));
            textCity.setTextColor(getResources().getColor(R.color.c3333));
            buttonSend.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_banner_left:
                onBackPressed();
                break;
            case R.id.text_banner_rigth:
                isEdit=true;
                swichStatus(isEdit);
                break;
        }
    }

    @OnClick({R.id.item_name1, R.id.item_name2, R.id.item_name3, R.id.item_name4, R.id.item_name5, R.id.item_name6,R.id.button_send})
    public void onMyClick(View v) {
        if (!isEdit)
        {
            return;
        }
        switch (v.getId()) {
            case R.id.item_name1:
                hideSoftInputFromWindow(textName);
                headImgPicker();
                break;
            case R.id.item_name2:
                //   intent=new Intent(this, );
                break;
            case R.id.item_name3:
                hideSoftInputFromWindow(textName);
                initNoLinkOptionsPicker();
                pvNoLinkOptions.show(textSex);
                break;
            case R.id.item_name4:
                hideSoftInputFromWindow(textName);
                initTimePicker();
                pvTime.show(textDate);
                break;
            case R.id.item_name5:
                hideSoftInputFromWindow(textName);
                //  initNoLinkOptionsPicker();
//                pvNoLinkOptions.show(textCity);
                break;
            case R.id.item_name6:
                hideSoftInputFromWindow(textName);
                Intent intent = new Intent(this, ProvinceAc.class);
                startActivityForResult(intent, 0x386);
                break;
            case R.id.button_send:
                String name = textName.getText().toString().replace(" ", "");
//                if (!(user.getHeadUrl() !=null||user.getHeadUrl_local()!=null)) {
//                    Toast.makeText(this, "请选择头像", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                if (name == null || name.length() < 1) {
                    Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (textCity.getText() == null || textCity.getText().length() < 1) {
                    Toast.makeText(this, "请选择城市", Toast.LENGTH_SHORT).show();
                    return;
                }
                user.setUserName(name);
                AbsP impPPersonal = new ImpPPersonal();
                impPPersonal.user_saveUserInfo(user);
                ShowMsgUtil.showLoadingDialog(this);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public  void netResponse(BaseResponse t) {
         ShowMsgUtil.hideLoadingDialog();
        if (t.getCode() == 200) {
            Toast.makeText(this,"用户资料保存成功",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.putExtra("cid", user.getCityId());
            intent.putExtra("uname", user.getUserName());
            intent.putExtra("cname", user.getCityName());
            if (user.getHeadUrl_local()!=null){
                intent.putExtra("headimg", user.getHeadUrl_local());
            }

            setResult(0x586, intent);
            finish();
        }else if (t.getCode()==4005){
            if((System.currentTimeMillis()-exitTime) > 2000){
                startActivity(new Intent(this,LoginAc.class));
                Toast.makeText(this,t.getMessage(),Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            }
        }
        else {
            Toast.makeText(this,t.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }


    private void initTimePicker() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(1949, 1, 1);
        Calendar endDate = Calendar.getInstance();
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                ((TextView) v).setText(TimeUtil.getTime(date));
                user.setBirthbay(date.getTime());
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, false, false, false, false})
                .setLabel("年", "月", "日", "点", "分", "")
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
    }

    private void initNoLinkOptionsPicker() {// 不联动的多级选项
        final List<String> list = new ArrayList<>();
        list.add("男");
        list.add("女");
        pvNoLinkOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                ((TextView) v).setText(list.get(options1));
                user.setSex(options1 + 1);
            }
        }).build();
        pvNoLinkOptions.setNPicker(list, null, null);
    }

    public void hideSoftInputFromWindow(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }


    private void headImgPicker() {
        if (alertDialog != null && alertDialog.isShowing()) {
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("");
        builder.setTitle("头像选择");
        builder.setPositiveButton("相机", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                File file = new File(Environment.getExternalStorageDirectory(), "/temp/head_img.jpg");
                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                Uri imageUri = Uri.fromFile(file);
                getTakePhoto().onPickFromCapture(imageUri);
            }
        });
        builder.setNegativeButton("相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getTakePhoto().onPickFromGallery();
            }
        });
        alertDialog = builder.create();
        alertDialog.show();
    }


    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        showImg(result.getImages());
    }

    private void showImg(ArrayList<TImage> images) {
        Glide.with(this).load(new File(images.get(images.size() - 1).getOriginalPath())).into(imgHead);
        user.setHeadUrl_local(images.get(images.size() - 1).getOriginalPath());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0x486) {
            textCity.setText(data.getStringExtra("cname"));
            user.setCityId(data.getStringExtra("cid"));
            user.setCityName(data.getStringExtra("cname"));
        }
    }


    @Override
    public void onBackPressed() {
        if (isEdit){
            startActivity(new Intent(this,PersonalAc.class));
        }
        finish();
    }
}
